<?php
namespace app\home\controller;
use \think\Validate;
use \think\Paginator;

class Comment extends \think\Controller
{

	public function addComment()
	{
		if( session('user_id') == NULL )
		{
			$this->error("请登录",'home/login/login');
		}

		$note_id = input('post.note_id');
		$content = input('post.comment_content');

		$rule = [
			'content'		=> 'require'
		];

		$msg = [
			'content.require'	=>  '内容不能为空'
		];

		$data = [
			'content'		=> $content
		];

		$validate = new Validate($rule,$msg);
		$result = $validate->check($data);

		if( ! $result)
		{
			$this->error($validate->getError());
		}

		$data = [
			//'user_id'		=> '1',
			'user_id'			=>  session('user_id'),
			'note_id'			=>  $note_id,
			'comment_content'	=>  $content,
			'addtime'       	=>  time(),
 		];

 		$ret = db('comment')->insert($data);
 		if( $ret ==false )
 		{
 			$this->error("提交失败");
 		}
 		$this->success("提交成功");

	}

public function showComment()
	{
		$pageno = input('get.pageno');
		$note_id = input('get.note_id');
		$pagesize = 1;
		$left = ($pageno - 1 ) * $pagesize;
		$clist = db('comment')->alias('a')->join('user b','a.user_id = b.user_id')->where("a.note_id={$note_id}")->field('a.*,b.user_name,b.user_img')->limit("{$left},{$pagesize}")->order("a.addtime desc")->select();
		foreach( $clist as $val )
		{
			$comment_id = $val['comment_id'];
			$reply = db('replycomment')->alias('a')->join('user b','a.user_id=b.user_id')->where("a.comment_id={$comment_id}")->field('a.*,b.user_name')->limit("0,2")->order("a.addtime desc")->select();
			$val['reply'] = $reply;
			$data[] = $val;
		}
		if( empty($clist) )
		{
			$this->error("没有啦");
		}

		//渲染模板输出
		$this->assign('clist',$data);
		$html = $this->fetch('comment_list');
		$this->success("成功","",$html);
		
		return view('note_detail');
	}


	public function addreply()
		{
		if( session('user_id') == NULL )
		{
			$this->error("请登录",'home/login/login');
		}
		$user_id = session('user_id'); 
		$note_id = input('post.note_id');
    	$comment_id = input('post.comment_id');
    	$content = input('post.content');

    	if ( $note_id == "") 
    	{
    		$this->error("参数错误","",1);
    	}

    	if( $content == "" )
    	{
    		$this->error("内容为空","",2);
    	}

    	$data = [
    		'user_id' 	  	 =>  $user_id,
    		'reply_content'  =>  $content,
    		'comment_id'  	 =>  $comment_id,
    		'note_id' 	  	 =>  $note_id,
    		'addtime'     	 =>  time(),
    	];
    	$ret = db('replycomment')->insert($data);

    	if ( $ret == NULL) 
    	{
    		$this->error("回复失败","",3);
    	}
    	$this->success("回复成功");
	}

}

